﻿using EasyDDD.AdminModule.Domain.AggregateSysAdmin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// using Microsoft.AspNetCore.Identity;

namespace EasyDDD.AdminModule.Application.CommandsSysAdmin
{
    [AutoMapperTo(typeof(SysAdmin))]

    public record SysAdminUpdateCommand : ICommand<SysAdmin>
    {
        public Guid Id { get; set; } = default!;
        public Guid RowVersion { get; set; } = default!;
        public short Status { get; set; } = default!;
        public string NickName { get; set; } = default!;
        public string UserName { get; set; } = default!;
        public string PhoneNumber { get; set; } = default!;
        public string Email { get; set; } = default!;
        public string Sex { get; set; } = default!;
        //public string Dept { get; set; } = default!;
        public string Remark { get; set; } = default!;
    }
    public class SysAdminUpdateCommandValidator : AbstractValidator<SysAdminUpdateCommand>
    {
        public SysAdminUpdateCommandValidator(Repository.SysAdminRepository repository)
        {
            var query = repository.AsQueryable();

            RuleFor(x => x.UserName).NotEmpty().MaximumLength(20)
                .WithMessage("用户名不能为空");
            RuleFor(x => x.PhoneNumber).NotEmpty().MaximumLength(20)
                .WithMessage("手机不能为空");

            RuleFor(x => x).Must(input => !query.Any(e => e.Id != input.Id && e.UserName == input.UserName))
                .WithMessage("用户名不能重复");
            RuleFor(x => x).Must(input => !query.Any(e => e.Id != input.Id && e.PhoneNumber == input.PhoneNumber))
                .WithMessage("手机不能重复");
            RuleFor(x => x).Must(input => !query.Any(e => e.Id != input.Id && e.Email == input.Email))
                .WithMessage("邮箱不能重复");
        }
    }
    public class SysAdminUpdateCommandHandler(
        //IMapper mapper,
        Repository.SysAdminRepository repository,
        ILogger<SysAdminUpdateCommandHandler> logger)
        : ICommandHandler<SysAdminUpdateCommand, SysAdmin>
    {
        public async Task<SysAdmin> Handle(SysAdminUpdateCommand request, CancellationToken cancellationToken)
        {
            logger.LogDebug("命令 SysAdminUpdateCommandHandler");
            var entity = await repository.GetAsync(request.Id, request.RowVersion);
            entity.Set(request.PhoneNumber, request.UserName, request.NickName, request.Remark);
            return entity;
        }
    }
}
